package student.aistar.day15.deadLock;

/**
 * 死锁
 */
public class DeadLockDemo{
    //临界资源
    //每个对象对应一个监视器锁[monitor对象]

    //当设置为静态资源, 两个线程都会竞争同一个资源, 肯定会发生死锁
    //当不设置时, 为不同资源, 不会发生死锁
    public static Object oo1 = new Object();
    public static Object oo2 = new Object();

    public static void main(String[] args) {
        Thread d1 = new D1();
        Thread d2 = new D2();

        d1.start();
        d2.start();
    }
}
class D1 extends  Thread{
    private DeadLockDemo dd = new DeadLockDemo();

    @Override
    public void run() {
        synchronized (dd.oo1){//申请到了oo1对象的锁资源
            System.out.println("=====111=====");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (dd.oo2){//申请到了oo1对象的锁资源
                System.out.println("=======22=======");
            }
        }
    }
}
class D2 extends Thread{
    private DeadLockDemo dd = new DeadLockDemo();

    @Override
    public void run() {
        synchronized (dd.oo2){
            System.out.println("====33====");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (dd.oo1){
                System.out.println("=====44=====");
            }
        }
    }
}